package com.amon.amonplayer;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;

import com.amon.amonplayer.live.LivePushActivity;
import com.amon.amonplayer.player.widget.VideoView;
import com.amon.amonplayer.record.VideoRecordActivity;
import com.amon.amonplayer.rxjava.Observable;
import com.amon.amonplayer.rxjava.schedulder.AndroidSchedulers;
import com.amon.amonplayer.rxjava.schedulder.Schedulers;
import com.amon.amonplayer.watchdog.ChoreographerMonitor;
import com.amon.butterknfie.annotation.BindView;
import com.amon.canary.IOCanary;
import com.amon.canary.NativeCrashMonitor;
import com.amon.canary.NativeThreadMonitor;

import java.io.File;

public class MainActivity extends AppCompatActivity {
    private File mMusicFile;
    private VideoView mVideoView;

    @BindView(R.id.play)
    Button mPlay;

    private Object lock1 = new Object();
    private Object lock2 = new Object();

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    String uri = "background.mp3";
    //String pushUri = "rtmp://ws.91go.vip/myapp/mystream";
    //String url = "http://218.92.0.8:2008/fseeca82d4.a.bdydns.com/1924164272/cloudmusic/ICQgMDAyNCAgMjA0IjA0OQ==/mv/34102/cfe0ffc1132c0159d5fcd97e41733e17.mp4?wsSecret=dd3907dcaa8f7d71685d5c3b597208e7&wsTime=1627563537&http_cdnfrom=bdcloud&max_age=31104000&r=2CZ5nbAdzLbnp%2BOMgS3Y%2BBSjibC2tVEvJRk6zwgZBx22QBZuGxvzQ7gt7gvCb7G%2FFzd1SqsXASlTZLIulW5ldq6JwEFZC0EYPr34yEcZIs1WMkb1m4IMimE701fwaFXZ9NsilEfnOQABnIfDXN8%2BEDy5SyqzFJP%2FVV%2BFPwSykwiTp8BaJwxCFKeSLjixz9aLZ1LaKARZWBY2nGdOz7I9gS%2Fb8kr97hJ50kqW5EfLZuA%3D&UYs5cp=hpmMlJaPwsvZhpmNmo6Wm8K-uoaGk5a6vMq-rrSStrC-vrjZhpmLlpKaws7JzcjKyczKys0~&sent_http_cdn-source=bdcloud&sent_http_access-control-allow-origin=*&sent_http_cdn-ip=240e%3Af7%3A8e00%3A400%3A%3Ab783%3Ab923&sent_http_access-control-allow-methods=GET%2CPOST%2COPTIONS&sent_http_access-control-allow-credentials=true&sent_http_cache=state&sent_http_cdn-user-ip=240e%3A37a%3A2561%3A9600%3A7151%3Aeb7%3A310d%3A8412&sent_http_access-control-allow-headers=DNT%2CX-CustomHeader%2CKeep-Alive%2CUser-Agent%2CX-Requested-With%2CIf-Modified-Since%2CCache-Control%2CContent-Type%2CRange&sent_http_access-control-expose-headers=Content-Range%2C%20Last-Modified";

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.e("TAG", "onCreate");

        ImageView imageView = findViewById(R.id.image_view);
        imageView.setImageResource(R.mipmap.ic_launcher);

        mVideoView = findViewById(R.id.videoview);
        mPlay = findViewById(R.id.play);
        mPlay.setOnClickListener(v -> {
            try {
                mMusicFile = new File(getExternalFilesDir(null).getAbsolutePath(), "fanren.flv");
                if (mMusicFile.exists()) {
                    Uri uriForFile = FileProvider.getUriForFile(getApplicationContext(),
                            "com.tpv.amonplayer.fileprovider", mMusicFile);
                    ParcelFileDescriptor fileDescriptor = getApplicationContext().
                            getContentResolver().openFileDescriptor(uriForFile, "r");
                    mVideoView.playFd(fileDescriptor.getFileDescriptor());
                } else {
                    mVideoView.playFd(uri);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        findViewById(R.id.camera).setOnClickListener(v -> {
            Intent intent = new Intent(this, VideoRecordActivity.class);
            startActivity(intent);
        });

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED ||
                ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED ||
                ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED ||
                ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
                        != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA,
                    Manifest.permission.RECORD_AUDIO}, 1);
            return;
        }

        findViewById(R.id.live).setOnClickListener(v -> {
            Intent intent = new Intent(this, LivePushActivity.class);
            startActivity(intent);
        });

        findViewById(R.id.pause).setOnClickListener(v -> {
            Log.e("TAG", "--->");
            Thread Thread1 = new Thread(() -> {
//                synchronized (lock1) {
//                    try {
//                        Thread.sleep(500);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    synchronized (lock2) {
//
//                    }
//                }
                LauncherState.INSTANCE.get(this);
            });
            Thread Thread2 = new Thread(()->{
//                synchronized (lock2) {
//                    try {
//                        Thread.sleep(500);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    synchronized (lock1) {
//
//                    }
//                }
                LauncherState.INSTANCE.get(this);
            });
            Thread Thread3 = new Thread(()-> {
//                try {
//                    Thread.sleep(500);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                NativeThreadMonitor.handle();
                LauncherState.INSTANCE.get(this);
            });
//            List<Thread> list = new ArrayList<>();
//            for (int i = 0; i < 1000; i++) {
//                Thread Thread4 = new Thread(()-> {
//                    LauncherState.INSTANCE.get(this);
//                });
//                list.add(Thread4);
//            }
//
//            for (Thread thread: list) {
//                thread.start();
//            }
//
//            Thread1.start();
//            Thread2.start();
//            Thread3.start();
//            try {
//                FileInputStream fis = new FileInputStream("/sdcard/Movies/iocanary.wmv");
//                int i = 50;
//                byte[] buf = new byte[512];
//                do {
//                    int count = fis.read(buf);
//                    Log.i("TAG", "i:" + i + "count:" + count);
//                } while (i-- > 0);
//                fis.close();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
        });

        ChoreographerMonitor choreographerMonitor = new ChoreographerMonitor();
        choreographerMonitor.start();

        NativeCrashMonitor nativeCrashMonitor = new NativeCrashMonitor();
        nativeCrashMonitor.init(crashInfo -> {

        });
        startThreadMonitor();
        IOCanary.hookCloseGuardReport();
        Observable.just("http://xxx.com")
                .map(BitmapFactory::decodeFile)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {

                });
    }

    private void startThreadMonitor() {
        int result = NativeThreadMonitor.monitorThread();
        Log.e("TAG", "monitorThread -> " + result);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mVideoView.stop();
    }
}